package com.mercenary.wein.screenControl.command.jobSchedual;

import com.mercenary.wein.screenControl.bean.CommandBean;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.ParseException;
import java.util.Random;

/**
 * Created by tuxiao on 2017/3/25.
 */
public class QuartzManager {
    private static SchedulerFactory sf = new StdSchedulerFactory();
    private static String RN_JOB_GROUP_NAME = "rightNowJob";
    private static String SCHEDULE_JOB_GROUP_NAME = "scheduleJob";
    private static String TRIGGER_GROUP_NAME = "trigger_group";

    public static void exeJob(Job taskJob,CommandBean commandBean)throws SchedulerException, ParseException{
        int mode = commandBean.getExeModeBean().getMode();
        if(mode==0){
            runJobRightNow(taskJob,commandBean);
        }else if(mode==1){
            runJobAtTime(taskJob,commandBean);
        }else if(mode==2){
            runJobCycle(taskJob,commandBean);
        }
    }

    /**
     * 立马执行的任务
     * @param taskJob
     * @throws SchedulerException
     * @throws ParseException
     */
    private static void runJobRightNow(Job taskJob, CommandBean commandBean)throws SchedulerException, ParseException{
        Scheduler sched = sf.getScheduler();
        String jobName = (commandBean.getExeModeBean()==null?"立即执行任务":commandBean.getExeModeBean().getJobName())
                +"-"+commandBean.getSerialNo()+"-"+commandBean.getSubmitTime();
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("commandBean",commandBean);
        JobDetail jobDetail = JobBuilder.newJob(taskJob.getClass())
                .withIdentity(jobName, RN_JOB_GROUP_NAME)
                .setJobData(jobDataMap)
                .build();//任务名，任务组，任务执行类
        //触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, TRIGGER_GROUP_NAME)
                .startNow()
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                )
                .build();
        sched.scheduleJob(jobDetail,trigger);
        //启动
        if(!sched.isShutdown())
            sched.start();
    }

    /** *//**
     * 添加一个定时任务，使用默认的任务组名，触发器名，触发器组名
     * @param taskJob    任务bean
     * @throws SchedulerException
     * @throws ParseException
     */
    private static void runJobAtTime(Job taskJob,CommandBean commandBean)
            throws SchedulerException, ParseException {
        Scheduler sched = sf.getScheduler();
        String jobName = wrapJobName(commandBean);
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("commandBean",commandBean);
        JobDetail jobDetail = JobBuilder.newJob(taskJob.getClass())
                .withIdentity(new JobKey(jobName, SCHEDULE_JOB_GROUP_NAME) )
                .setJobData(jobDataMap)
                .build();//任务名，任务组，任务执行类
        //触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(commandBean.getExeDate())
                .withIdentity(new TriggerKey(jobName,TRIGGER_GROUP_NAME))
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0)
                )
                .build();
        sched.scheduleJob(jobDetail,trigger);
        //启动
        if(!sched.isShutdown())
            sched.start();
    }

    private static void runJobCycle( Job taskJob ,CommandBean commandBean )
            throws SchedulerException, ParseException {
        Scheduler sched = sf.getScheduler();
        String jobName = wrapJobName(commandBean);
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("commandBean",commandBean);
        JobDetail jobDetail = JobBuilder.newJob(taskJob.getClass())
                .setJobData(jobDataMap)
                .withIdentity(new JobKey(jobName, SCHEDULE_JOB_GROUP_NAME) )
                .build();//任务名，任务组，任务执行类
        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .repeatForever();
        if(commandBean.getTimeUnit()==0){
            simpleScheduleBuilder.withIntervalInMinutes(commandBean.getInterval());
        }else if(commandBean.getTimeUnit()==1){
            simpleScheduleBuilder.withIntervalInHours(commandBean.getInterval());
        }else {
            simpleScheduleBuilder.withIntervalInHours(commandBean.getInterval()*24);
        }
        //触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(commandBean.getExeDate())
                .withIdentity(new TriggerKey(jobName,TRIGGER_GROUP_NAME))
                .withSchedule(
                        simpleScheduleBuilder
                )
                .build();
        sched.scheduleJob(jobDetail,trigger);
        //启动
        if(!sched.isShutdown())
            sched.start();
    }

//    /** *//**
//     * 修改一个任务的触发时间(使用默认的任务组名，触发器名，触发器组名)
//     * @param jobName
//     * @param time
//     * @throws SchedulerException
//     * @throws ParseException
//     */
//    public static void modifyJobTime(String jobName,String time)
//            throws SchedulerException, ParseException{
//        Scheduler sched = sf.getScheduler();
//        Trigger trigger =  sched.getTrigger(jobName,TRIGGER_GROUP_NAME);
//        if(trigger != null){
//            CronTrigger  ct = (CronTrigger)trigger;
//            ct.setCronExpression(time);
//            sched.resumeTrigger(jobName,TRIGGER_GROUP_NAME);
//        }
//    }
//
//    /** *//**
//     * 修改一个任务的触发时间
//     * @param triggerName
//     * @param triggerGroupName
//     * @param time
//     * @throws SchedulerException
//     * @throws ParseException
//     */
//    public static void modifyJobTime(String triggerName,String triggerGroupName,
//                                     String time)
//            throws SchedulerException, ParseException{
//        Scheduler sched = sf.getScheduler();
//        Trigger trigger =  sched.getTrigger(triggerName,triggerGroupName);
//        if(trigger != null){
//            CronTrigger  ct = (CronTrigger)trigger;
//            //修改时间
//            ct.setCronExpression(time);
//            //重启触发器
//            sched.resumeTrigger(triggerName,triggerGroupName);
//        }
//    }
//
    /** *//**
     * 移除一个任务(使用默认的任务组名，触发器名，触发器组名)
     * @param bean
     * @throws SchedulerException
     */
    public static void removeJob(CommandBean bean)
            throws SchedulerException{
        String jName = wrapJobName(bean);
        Scheduler sched = sf.getScheduler();
        sched.pauseTrigger(new TriggerKey(jName,TRIGGER_GROUP_NAME));//停止触发器
        sched.unscheduleJob(new TriggerKey(jName,TRIGGER_GROUP_NAME));//移除触发器
        sched.deleteJob(new JobKey(jName,SCHEDULE_JOB_GROUP_NAME));//删除任务
    }
//
//    /** *//**
//     * 移除一个任务
//     * @param jobName
//     * @param jobGroupName
//     * @param triggerName
//     * @param triggerGroupName
//     * @throws SchedulerException
//     */
//    public static void removeJob(String jobName,String jobGroupName,
//                                 String triggerName,String triggerGroupName)
//            throws SchedulerException{
//        Scheduler sched = sf.getScheduler();
//        sched.pauseTrigger(triggerName,triggerGroupName);//停止触发器
//        sched.unscheduleJob(triggerName,triggerGroupName);//移除触发器
//        sched.deleteJob(jobName,jobGroupName);//删除任务
//    }

    public static void test(TestJob taskJob)throws SchedulerException, ParseException{
        Scheduler sched = sf.getScheduler();
        JobDetail jobDetail = JobBuilder.newJob(taskJob.getClass())
                .withIdentity("test"+new Random().nextInt(10000), RN_JOB_GROUP_NAME)
                .build();//任务名，任务组，任务执行类
        //触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("test"+new Random().nextInt(10000), TRIGGER_GROUP_NAME)
                .startNow()
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                )
                .build();
        sched.scheduleJob(jobDetail,trigger);
        //启动
        if(!sched.isShutdown())
            sched.start();
    }

    public static String wrapJobName(CommandBean bean){
        return bean.getSerialNo()+"-"+bean.getExeModeBean().getJobName()+"-"+bean.getZid();
    }
}
